<?php
namespace app\api\controller;

use app\admin\model\system\System;
use app\admin\model\useraccount\Useraccount;
use app\common\controller\Api;
use PHPMailer\PHPMailer\PHPMailer;
use think\Db;
use think\Exception;
use think\Session;

class Withdraw extends Api{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function apply(){
        //$this->error('提现功能正在升级中...');
        $amount = $this->request->param('amount');
        $tongdao = $this->request->param('tongdao');
        $code = $this->request->param('code');
        $pay_password = $this->request->param('pay_password');
        $userinfo = $this->auth->getUserinfo();
        $userModel = new \app\admin\model\User();
        $userinfo = $userModel->where(['id'=>$userinfo['id']])->find()->toArray();
        if($userinfo['pay_password'] ==''){
            return json_encode([
                'code'=>102,
                'msg'=>'您还未设置交易密码',
                'data'=>[]
            ]);
        }
        $new_password = md5($pay_password);
        if($new_password!=$userinfo['pay_password']){
            $this->error('交易密码不正确');
        }
        $sess_code = Session::get('WITHDRAW_CODE');
        if($sess_code!=$code){
            $this->success('验证码不正确');
        }
        if(!$amount){
            $this->error('金额不能为空');
        }
        if($tongdao==1 || $tongdao==2 || $tongdao==3){
            if($amount > $userinfo['shouyi_balance']){
                $this->error('余额不足');
            }
        }else if($tongdao==4 || $tongdao==5){
            if($amount > $userinfo['usdt_balance']){
                $this->error('余额不足');
            }
        }

        if($userinfo['is_freeze']==1){
            $this->error('您的帐户被冻结，不能提现');
        }

        if($tongdao==1){
            if($userinfo['is_wx']==0){
                return json_encode([
                    'code'=>101,
                    'msg'=>'您还未绑定微信收款码',
                    'data'=>[]
                ]);
            }else{
                $useraccountModel = new Useraccount();
                $accountinfo = $useraccountModel->where(['user_id'=>$userinfo['id']])->find()->toArray();
                $img = $accountinfo['wx_img'];
                $wallet_address = '';
                $unit = 1;
                $unit_name='人民币';
            }
        }elseif ($tongdao==2){
            if($userinfo['is_zfb']==0){
                return json_encode([
                    'code'=>101,
                    'msg'=>'您还未绑定支付宝收款码',
                    'data'=>[]
                ]);
            }else{
                $useraccountModel = new Useraccount();
                $accountinfo = $useraccountModel->where(['user_id'=>$userinfo['id']])->find()->toArray();
                $img = $accountinfo['zfb_img'];
                $wallet_address = '';
                $unit = 1;
                $unit_name='人民币';
            }
        }elseif ($tongdao==3){
            if($userinfo['is_sh']==0){
                return json_encode([
                    'code'=>101,
                    'msg'=>'您还未设置纷享生活收款码',
                    'data'=>[]
                ]);
            }else{
                $useraccountModel = new Useraccount();
                $accountinfo = $useraccountModel->where(['user_id'=>$userinfo['id']])->find()->toArray();
                $img = $accountinfo['sh_img'];
                $wallet_address = '';
                $unit = 1;
                $unit_name='人民币';
            }
        }else if($tongdao==4){
            if($userinfo['is_bep']==0){
                return json_encode([
                    'code'=>101,
                    'msg'=>'您还未设置BEP收款码',
                    'data'=>[]
                ]);
            }else{
                $useraccountModel = new Useraccount();
                $accountinfo = $useraccountModel->where(['user_id'=>$userinfo['id']])->find()->toArray();
                $img = $accountinfo['sh_img'];
                $wallet_address = '';
                $unit = 2;
                $unit_name='USDT';
            }
        }else if($tongdao==5){
            if($userinfo['is_trc']==0){
                return json_encode([
                    'code'=>101,
                    'msg'=>'您还未设置TRC收款码',
                    'data'=>[]
                ]);
            }else{
                $useraccountModel = new Useraccount();
                $accountinfo = $useraccountModel->where(['user_id'=>$userinfo['id']])->find()->toArray();
                $img = $accountinfo['sh_img'];
                $wallet_address = '';
                $unit = 2;
                $unit_name='USDT';
            }
        }

        //查一下是否有申请中的提现
        $withdrawModel = new \app\admin\model\withdraw\Withdraw();
        $withdrawinfo = $withdrawModel->where(['user_id'=>$userinfo['id'],'status'=>0])->find();
        if($withdrawinfo){
            $this->error('您有待审核的提现，请不要重复申请');
        }
        Db::startTrans();
        try{
            //先扣除用户的hc_balance
            $userModel = new \app\admin\model\User();
            $userModel->where(['id'=>$userinfo['id']])->update(['shouyi_balance'=>$userinfo['shouyi_balance']-$amount]);
            //开始提现
            $indata['user_id'] = $userinfo['id'];
            $indata['amount'] = $amount;
            $indata['unit'] = $unit;
            $indata['unit_name'] = $unit_name;
            $indata['create_time'] = time();
            $indata['wallet_address'] = $wallet_address;
            $indata['tongdao'] = $tongdao;
            $indata['img'] = $img;
            $withdrawModel->insert($indata);
            $systemModel = new System();
            $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
            /*if($systeminfo['email']!='') {
                $emailList = explode(",", $systeminfo['email']);
                $emailList = array_filter(array_map('trim', $emailList));

                $mail = new PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = 'smtp.qq.com';
                $mail->SMTPAuth = true;
                $mail->Username = '3906570020@qq.com';
                $mail->Password = 'ynfxafymcczicejf';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = 587;
                $mail->CharSet = 'UTF-8';
                $mail->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );

                $successCount = 0;
                $failCount = 0;
                $failEmails = [];

                foreach ($emailList as $email) {
                    if (!$this->checkemail($email)) {
                        $failCount++;
                        $failEmails[] = $email . '(格式无效)';
                        continue;
                    }

                    try {
                        // 清理之前的收件人
                        $mail->clearAddresses();
                        $mail->clearCCs();
                        $mail->clearBCCs();
                        $mail->clearReplyTos();
                        $mail->clearAllRecipients();
                        $mail->clearAttachments();
                        $mail->clearCustomHeaders();

                        // 设置新的收件人
                        $mail->setFrom('3906570020@qq.com', '合创城');
                        $mail->addAddress($email);

                        // 邮件内容
                        $mail->isHTML(true);
                        $mail->Subject = '用户提现提醒';
                        $mail->Body = '用户' . $userinfo['id'] . '申请提现' . $amount . 'USDT' . '请尽快审核';
                        $mail->AltBody = "用户提现提醒";

                        if ($mail->send()) {
                            $successCount++;
                        } else {
                            $failCount++;
                            $failEmails[] = $email;
                        }
                    } catch (Exception $e) {
                        $failCount++;
                        $failEmails[] = $email . '(' . $e->getMessage() . ')';
                    }
                    usleep(100000);
                }
            }*/
            Db::commit();
            $this->success('申请成功，请等待管理员审核');
        }catch(Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function checkemail($email){
        return filter_var(trim($email), FILTER_VALIDATE_EMAIL) !== false;
    }

    public function withdrawlist(){
        $userinfo = $this->auth->getUserinfo();
        $withdrawModel = new \app\admin\model\withdraw\Withdraw();
        $withdrawlist = collection($withdrawModel->where(['user_id'=>$userinfo['id']])->select());
        if($withdrawlist){
            $withdrawlist = $withdrawlist->toArray();
            $newlist=[];
            foreach ($withdrawlist as $k=>$v){
                $newlist[$k]['id']=$v['id'];
                $newlist[$k]['amount']=$v['amount'];
                $newlist[$k]['unit_name']=$v['unit_name'];
                $newlist[$k]['create_time']=date("Y-m-d H:i:s",$v['create_time']);
                $newlist[$k]['real_amount']=$v['real_amount'];
                $newlist[$k]['shouxufei']=$v['shouxufei'];
                if($v['status']==0){
                    $newlist[$k]['status_name']='待审核';
                }else if($v['status']==1){
                    $newlist[$k]['status_name']='提现成功';
                }else if($v['status']==2){
                    $newlist[$k]['status_name']='提现失败';
                }
                $newlist[$k]['reason']=$v['reason'];
                $newlist[$k]['wallet_address']=$v['wallet_address'];
            }
            $this->success('成功',$newlist);
        }else{
            $this->success('成功',[]);
        }
    }
}